<template>
  <div>
    <glsx-dialog :show="value" :title="titleList[classify]" width="70%" @close="closeDialog">
      <div class="feedback_box" v-loading="pageLoading">

        <!-- 左边表单 开始 -->
        <div class="left_form" ref="leftForm">
          <el-form class="el_form" ref="addForm" :model="addForm" :rules="addFormRules" size="small"
            label-width="150px">
            <el-form-item label="待反馈客户：" required v-if="classify == 'wait'">
              <div class="customer_list">
                <el-tag v-for="(item, index) in customerList" :type="tagActive == item.id?'':'info'" :effect="tagActive == item.id ? 'dark' : 'plain'" :key="`customer_${index}`" class="el_tag" size="small" @click="chooseCustomer(item)">{{ item.name }}/{{
                    item.phone
                }}
                </el-tag>
              </div>
            </el-form-item>
            <el-form-item label="客户姓名：" prop="name">
              <el-input type="text" v-model.trim="addForm.name" class="a_input" placeholder="请输入客户姓名"
                v-if="classify == 'otherBack'"></el-input>
              <div class="el_form_item" v-else>
                <!-- <el-autocomplete v-model="addForm.name" class="a_input" :fetch-suggestions="getList"
                  placeholder="请输入客户姓名" @select="selectCustomer">
                  <template slot-scope="{ item }">
                    {{ item.name + '/' + item.phone }}
                  </template>
                </el-autocomplete> -->
                <el-select v-model="addForm.name" filterable remote class="a_input" placeholder="请输入关键词"
                  :remote-method="getList" :loading="loading">
                  <el-option v-for="(item,index) in userList" :key="index" :label="(item.name + '/' + item.phone)" :value="item.id" @click.native="selectCustomer(item)">
                  </el-option>
                </el-select>
                <div class="show_tips">(如到店登记名称不一致可<button class="a_link" :disabled="!orderId" @click.prevent="openEditDialog('name')">点击修改</button>)
                </div>
              </div>
            </el-form-item>
            <el-form-item label="客户电话：" prop="phone">
              <el-input type="text" v-model.trim="addForm.phone" class="a_input" placeholder="请输入客户电话" maxlength="11"
                v-if="classify == 'otherBack'"></el-input>
              <div class="el_form_item" v-else>
                <el-input type="text" v-model.number="addForm.phone" readonly class="a_input" maxlength="11"
                  placeholder="请输入客户电话"></el-input>
                <div class="show_tips">(如到店登记电话不一致可<button class="a_link" :disabled="!orderId" @click.prevent="openEditDialog('phone')">点击修改</button>)
                </div>
              </div>
            </el-form-item>
            <el-form-item label="预约时间：" prop="appointmentTime">
              <el-date-picker v-model="addForm.appointmentTime" class="a_input" type="datetime" placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="是否到店：" prop="arrivedStatus" v-if="classify != 'refund'">
              <el-radio-group v-model="addForm.arrivedStatus" @change="setHeight">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <template v-if="addForm.arrivedStatus == 1">
              <el-form-item label="是否成交：" prop="dealStatus" v-if="classify != 'refund'">
                <el-radio-group v-model="addForm.dealStatus" @change="onStatusChange">
                  <el-radio :label="8">是</el-radio>
                  <el-radio :label="7">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <template v-if="addForm.dealStatus == 8">
                <el-form-item :label="classify == 'refund' ? '成交金额减少：' : '成交金额：'" prop="dealAmount">
                  <el-input type="text" v-model="addForm.dealAmount" class="a_input"></el-input>
                </el-form-item>
                <el-form-item :label="classify == 'refund' ? '收款金额减少：' : '收款金额：'" prop="collectMoney">
                  <el-input type="text" v-model="addForm.collectMoney" class="a_input"></el-input>
                </el-form-item>
              </template>
              <el-form-item label="反馈内容：" prop="feedbackContent">
                <el-input type="textarea" v-model="addForm.feedbackContent" rows="5" resize="none" class="a_input">
                </el-input>
                <!-- <wang-editor v-model="addForm.feedbackContent" :menus="[]" :showFullScreen="false" height="140"></wang-editor> -->
              </el-form-item>
              <el-form-item label="预计下次复诊时间：" v-if="classify != 'refund'">
                <el-date-picker v-model="addForm.furtherConsultTime" class="a_input" type="datetime"
                  placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="口腔片：" prop="oralCavityPics" v-if="classify != 'refund'">
                <image-upload v-model="addForm.oralCavityPics" limit="3" size="small"></image-upload>
              </el-form-item>
            </template>
            <el-form-item label="跟进分工：" prop="followupParty" v-if="classify != 'refund'">
              <el-radio-group v-model="addForm.followupParty">
                <el-radio :label="1">门诊跟进</el-radio>
                <el-radio :label="2">平台跟进</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="退款凭证：" prop="refundVoucher" v-if="classify == 'refund'">
              <image-upload v-model="addForm.refundVoucher" limit="3" size="small"></image-upload>
            </el-form-item>

          </el-form>
        </div>
        <!-- 左边表单 end -->

        <!-- 右边反馈历史 开始 -->
        <div class="right_list" v-if="historyList && historyList.length">
          <div class="head">历史反馈</div>
          <el-scrollbar class="" :style="`height:${maxHeight}px;`">
            <div class="cell_box" v-for="(item, index) in historyList" :key="`history_${index}`">
              <div class="cell" v-if="item.feedbackTime">
                <div class="name">反馈时间：</div>
                <div class="txt">{{ item.feedbackTime }}</div>
              </div>
              <div class="cell" v-if="item.dealStatus">
                <div class="name">成交情况：</div>
                <div class="txt">{{ FEEDBACKDEALSTATUS[item.dealStatus] }}</div>
              </div>
              <div class="cell" v-if="item.dealAmount">
                <div class="name">成交金额：</div>
                <div class="txt">{{ item.dealAmount }}</div>
              </div>
              <div class="cell" v-if="item.collectMoney">
                <div class="name">收款金额：</div>
                <div class="txt">{{ item.collectMoney }}</div>
              </div>
              <div class="cell" v-if="item.feedbackContent">
                <div class="name">反馈内容：</div>
                <div class="txt" v-html="item.feedbackContent ? item.feedbackContent.replace(/\n/g, '<br/>') : ''">
                </div>
              </div>
              <div class="cell" v-if="item.furtherConsultTime">
                <div class="name">预计下次复诊时间：</div>
                <div class="txt">{{ item.furtherConsultTime }}</div>
              </div>
              <div class="cell" v-if="item.followupParty">
                <div class="name">跟进分工：</div>
                <div class="txt">{{ FEEDBACKFOLLOWUPPARTY[item.followupParty] }}</div>
              </div>
            </div>
          </el-scrollbar>
        </div>
        <!-- 右边反馈历史 end -->
      </div>

      <div slot="footer">
        <el-button type="primary" size="small" :loading="loading" @click="saveInfo()">保存</el-button>
        <el-button type="default" size="small" @click="closeDialog()">取消</el-button>
      </div>
    </glsx-dialog>

    <!-- 修改姓名、电话弹框 开始 -->
    <glsx-dialog :show="showDialog" width="460px" title="修改姓名">
      <div>
        <el-form ref="editForm" :model="editForm" :rules="addFormRules">
          <el-form-item label="客户姓名：" prop="name" v-if="currentId == 'name'">
            <el-input v-model.trim="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="客户电话：" prop="phone" v-if="currentId == 'phone'">
            <el-input v-model.trim="editForm.phone" maxlength="11"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" size="small" :loading="loading" @click="saveCustomer()">保存</el-button>
        <el-button type="default" size="small" @click="closeEditDialog()">取消</el-button>
      </div>
    </glsx-dialog>
    <!-- 修改姓名、电话弹框 end -->

  </div>
</template>
<script>
import { deepClone, showToast } from "@/common/util";
import { Validator,IS_DECIMAL,IS_MINUS_DECIMAL } from "@/common/validator";
import ImageUpload from "@/components/upload/upload.vue";
import { FEEDBACKDEALSTATUS, FEEDBACKFOLLOWUPPARTY } from '@/common/constants'
import {
  BASEURL,
  GET_OFEEDBACK_INFO,
  ADD_OFEEDBACK_INFO,
  GET_OFEEDBACK_ORDERINFO,
  EDIT_OFEEDBACK_INFO,
  GET_OFEEDBACK_HISTORY,
  GET_OFEEDBACK_ORDERSEARCH,
  GET_OFEEDBACK_ORDER,
  MODIFY_CUSTOMER_INFO
} from "@/http/feedback";
export default {
  name: "UpdateFeedback",
  props: {
    id: {
      type: [String, Number],
      default: "",
    },
    value: {
      type: Boolean,
      default: false,
    },
    feedbackId: {
      type: [String, Number],
      default: "",
    },
    classify: {
      type: String,
      default: ''   // 待反馈录入：wait，再到店客户录入：reback， 其他到店录入：otherBack,   退款录入：refund, 更新反馈：update
    }
  },
  components: {
    ImageUpload,
  },
  watch: {
    id: {
      handler: function (n, m) {
        if (n) {
          this.orderId = n
          this.getInfo(n);
          this.getHistory(n)
        }
      },
      immediate: true,
    },
    feedbackId: {
      handler: function (n, m) {
        if (n) {
          //this.orderId = n
          // 预约ID
          this.getFeedbackInfo(n);
        }
      },
      immediate: true,
    },
    classify: {
      handler: function (n, o) {
        let id = this.addForm.dealStatus
        if (n) {
          console.log(n)
          this.getCustomer(n)
          this.setFormRules(n)
        }
        if (n == 'refund') {
          id = 9
        }
        this.$set(this.addForm, 'feedbackContent', this.defaultTips[id])

      },
      immediate: true
    }

  },
  data() {
    return {
      pageLoading: true,
      addForm: { dealStatus: 8, arrivedStatus: 1 },
      addFormRules: {
        name: [{ required: true, message: "请输入客户姓名", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入客户电话", trigger: "blur" },
          {
            pattern: Validator.PHONEREG,
            message: "客户电话格式不正确",
            trigger: "blur",
          },
        ],
        appointmentTime: [
          { required: true, message: "请选择预约时间", trigger: "change" },
        ],
        arrivedStatus: [
          { required: true, message: "请选择是否到店", trigger: "change" },
        ],
        dealStatus: [
          { required: true, message: "请选择是否成交", trigger: "change" },
        ],
        feedbackContent: [
          { required: true, message: "请输入反馈内容", trigger: "blur" },
        ],
        followupParty: [
          { required: true, message: "请选择跟进分工", trigger: "change" },
        ],
        collectMoney: [],
        dealAmount: []
      },
      loading: false,
      bloading: false,
      randomKey: "",
      rules: {},
      historyList: [],
      defaultTips: {
        8: '1、客户主诉：\n2、检查结果：\n3、面诊医生：\n4、接诊咨询：\n5、成交详情：',
        7: '1、客户主诉：\n2、检查结果：\n3、面诊医生：\n4、接诊咨询师：\n5、未成交原因：',
        9: '1、退款原因：\n2、退款详细情况：',
      },
      FEEDBACKDEALSTATUS,
      FEEDBACKFOLLOWUPPARTY,
      maxHeight: '',
      customerList: [],
      tagActive: '',
      titleList: {
        'wait': '待反馈录入',
        'reback': '再到店客户录入',
        'otherBack': '其他到店录入',
        'refund': '退款录入',
        'update': '更新反馈',
        'add': '新增反馈'
      },
      orderId: '',
      showDialog: false,
      editForm: {},
      editFormRules: {},
      currentId: '',
      userList:[]
    };
  },
  created() {
    if (!this.id && !this.feedbackId) {
      this.pageLoading = false;
    }

  },
  mounted() {
    let _this = this
    _this.setHeight()
  },
  methods: {
    // 获取预约详情
    getInfo(id) {
      GET_OFEEDBACK_ORDERINFO({ id: id }).then((res) => {
        this.pageLoading = false;
        let obj = res.data || {};
        this.$set(this.addForm, "name", obj.name);
        this.$set(this.addForm, "phone", obj.phone);
        this.$set(this.addForm, "appointmentTime", obj.appointmentTime);

      });
    },

    // 获取反馈详情
    getFeedbackInfo(id) {
      GET_OFEEDBACK_INFO({ id: id }).then(res => {
        this.pageLoading = false
        let obj = res.data || {}
        let options = {}
        options.name = obj.name
        options.phone = obj.phone
        options.appointmentTime = obj.appointmentTime
        options.arrivedStatus = obj.arrivedStatus
        options.dealStatus = obj.dealStatus
        options.dealAmount = obj.dealAmount
        options.collectMoney = obj.collectMoney
        options.feedbackContent = obj.feedbackContent
        options.furtherConsultTime = obj.furtherConsultTime
        options.followupParty = obj.followupParty

        this.orderId = obj.orderId


        if (obj.oralCavityPics) {
          let arr = []
          let list = obj.oralCavityPics.split(',');
          list.map(k => {
            arr.push({
              name: k,
              path: k,
              url: BASEURL + k
            })
          })
          options.oralCavityPics = arr;
        }

        console.log(obj.refundVoucher)
        if(obj.refundVoucher){
          options.refundVoucher = obj.refundVoucher.split(',')
        }


        this.$set(this, "addForm", options);
      });
    },

    // 保存数据
    saveInfo() {
      let _this = this;
      console.log(this.addForm)
      _this.$refs.addForm.validate((valid) => {
        if (!valid) {
          return false;
        }

        let oParams = _this.getParams();
        oParams.dealType = _this.classify == 'refund' ? 6 : 5
        _this.loading = true;

        // 编辑反馈
        if (_this.feedbackId) {
          oParams.id = _this.feedbackId
          EDIT_OFEEDBACK_INFO(oParams).then((res) => {
            _this.loading = false;
            if (res.code == 200) {
              showToast({
                message: "保存成功",
                type: "success",
              });
              _this.$emit("input", false);
              _this.$emit("change", true);
            }
          });
          return false;
        }

        // 新增反馈
        ADD_OFEEDBACK_INFO(oParams).then((res) => {
          _this.loading = false;
          if (res.code == 200) {
            showToast({
              message: "保存成功",
              type: "success",
            });
            _this.$emit("input", false);
            _this.$emit("change", true);
          }
        });
      });
    },

    // 关闭弹框
    closeDialog() {
      this.$emit('input', false)
    },

    // 获取参数
    getParams() {
      let o = deepClone(this.addForm);
      let oParams = {};

      oParams.orderId = this.orderId;
      oParams.name = o.name;
      oParams.phone = o.phone;
      oParams.arrivedStatus = o.arrivedStatus;
      oParams.followupParty = o.followupParty;
      oParams.appointmentTime = o.appointmentTime

      if (o.arrivedStatus == 1) {
        oParams.dealStatus = o.dealStatus
        oParams.feedbackContent = o.feedbackContent
        oParams.furtherConsultTime = o.furtherConsultTime
        console.log(o.oralCavityPics)
        if (o.oralCavityPics) {
          let arr = [];
          o.oralCavityPics.map((k) => {
            if(typeof k == 'string'){
              arr.push(k)
            }else{
              arr.push(k.path);
            }
          });
          oParams.oralCavityPics = arr.toString();
        }

        if (o.dealStatus == 8) {
          oParams.dealAmount = o.dealAmount;
          oParams.collectMoney = o.collectMoney;
        }
      }

      // 退款时，退款凭证
      if (this.classify == 'refund' && o.refundVoucher) {
        let refundList = []
        o.refundVoucher.map((k) => {
          refundList.push(k.path);
        });
        oParams.refundVoucher = refundList.toString();
      }

      return oParams;
    },

    // 获取历史反馈
    getHistory(id) {
      GET_OFEEDBACK_HISTORY({ orderId: id }).then(res => {
        this.historyList = res.data || []
      })
    },

    // 监听是否成交改变
    onStatusChange(e) {
      this.$set(this.addForm, 'feedbackContent', this.defaultTips[e])
      this.setHeight()
    },

    // 设置最大高度
    setHeight() {
      let _this = this
      _this.maxHeight = 0;
      _this.$nextTick(function () {
        let o = _this.$refs.leftForm;
        _this.maxHeight = o.offsetHeight
      })
    },

    // 获取待反馈客户列表
    getCustomer(id) {
      if (!id || id == 'refund') {
        return false;
      }
      let oParams = {}
      oParams.pageNumber = 1;
      oParams.pageSize = 20;
      oParams.pageType = 0;
      oParams.fullPhone = true
      oParams.ofbStatus = 0
      GET_OFEEDBACK_ORDERSEARCH(oParams).then(res => {
        let obj = res.data || {}
        this.customerList = obj.list || []
      })
    },

    // 选择客户
    chooseCustomer(row) {
      this.$set(this.addForm, "name", row.name);
      this.$set(this.addForm, "phone", row.phone);
      this.$set(this.addForm, "appointmentTime", row.appointmentTime);
      this.orderId = row.id
      this.tagActive = row.id
    },

    // 设置校验规则
    setFormRules(e) {
      let o = [];
      let n = [];
      if (e == 'refund') {
        o = [
          { required: true, message: "请输入收款金额减少", trigger: "blur" },
          { validator: IS_MINUS_DECIMAL,message: "退款时，收款金额减少必须为负数且最多两位小数", trigger: 'blur' },
          {
            pattern: Validator.ISNEGATIVENUMBER,
            message: "退款时，收款金额减少只能为负数",
            trigger: "blur",
          }
        ]
        n = [
          { required: true, message: "请输入成交金额减少", trigger: "blur" },
          { validator: IS_MINUS_DECIMAL,message: "退款时，成交金额减少必须为负数且最多两位小数", trigger: 'blur' },
          {
            pattern: Validator.ISNEGATIVENUMBER,
            message: "退款时，成交金额减少只能为负数",
            trigger: "blur",
          },
        ];
      } else {
        o = [
          { required: true, message: "请输入收款金额", trigger: "blur" },
          // { type: "number", message: "收款金额必须为数字", trigger: "blur" },
          { validator: IS_DECIMAL,message: "收款金额必须为数字最多两位小数", trigger: 'blur' },
          // {
          //   pattern: Validator.ISDECIMAL,
          //   message: "收款金额不能为负数",
          //   trigger: "blur",
          // },
        ];
        n = [
          { required: true, message: "请输入成交金额", trigger: "blur" },
          // { type: "number", message: "成交金额必须为数字", trigger: "blur" },
          { validator: IS_DECIMAL,message: "成交金额必须为数字最多两位小数", trigger: 'blur' },
          // {
          //   pattern: Validator.ISDECIMAL,
          //   message: "成交金额不能为负数",
          //   trigger: "blur",
          // },
        ];
      }
      this.$set(this.addFormRules, "collectMoney", o);
      this.$set(this.addFormRules, "dealAmount", n);
    },

    // 模糊搜索客户
    async getList(term) {
      if (!term || term.length < 2) {
        return false;
      }
      let res = await GET_OFEEDBACK_ORDER({ term: term })
      this.userList = res.data||[]
    },

    // 选择客户
    selectCustomer(row) {
      console.log(row)
      this.$set(this.addForm, "name", row.name);
      this.$set(this.addForm, "phone", row.phone);
      this.$set(this.addForm, "appointmentTime", row.appointmentTime);
      this.orderId = row.id
    },

    // 关闭修改姓名、电话弹框
    closeEditDialog() {
      this.showDialog = false
    },

    // 打开修改姓名、电话弹框
    openEditDialog(id) {
      this.editForm = deepClone(this.addForm)
      this.editFormRules = deepClone(this.addFormRules)
      this.showDialog = true
      this.currentId = id
    },

    // 保存客户姓名、电话
    saveCustomer() {
      let o = this.editForm;
      let _this = this;
      this.$refs.editForm.validate(valid => {
        if (!valid) {
          return false;
        }

        let oParams = {}
        oParams.orderId = _this.orderId;
        oParams[_this.currentId] = o[_this.currentId];
        MODIFY_CUSTOMER_INFO(oParams).then(res => {
          if (res.code == 200) {
            _this.$set(_this.addForm, _this.currentId, o[_this.currentId])
            _this.showDialog = false
          }
        })
      })
    }


  },
};
</script>
<style lang="scss" scoped>
@import '@/assets/style/updateFeedback.scss';
</style>